<template>
  <div class="app-container">
    <!-- 搜索和操作工具栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="请输入文档标题"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.docType" placeholder="文档类型" clearable style="width: 120px" class="filter-item">
        <el-option
          v-for="item in docTypeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 120px" class="filter-item">
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        新建文档
      </el-button>
      
      <!-- 导入导出组件 -->
      <data-io
        :columns="exportColumns"
        :data="list"
        fileName="文档记录"
        :pdf-options="pdfOptions"
        @import="handleImport"
      />
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文档标题" prop="title" min-width="200">
        <template slot-scope="{row}">
          <el-link type="primary" @click="handleView(row)">{{ row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="文档类型" prop="docType" width="100">
        <template slot-scope="{row}">
          {{ getDocTypeName(row.docType) }}
        </template>
      </el-table-column>
      <el-table-column label="紧急程度" prop="urgencyLevel" width="100">
        <template slot-scope="{row}">
          <el-tag :type="getUrgencyType(row.urgencyLevel)">
            {{ getUrgencyName(row.urgencyLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="密级" prop="securityLevel" width="100">
        <template slot-scope="{row}">
          <el-tag :type="getSecurityType(row.securityLevel)">
            {{ getSecurityName(row.securityLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="createUserName" width="120" />
      <el-table-column label="创建时间" prop="createTime" width="160" />
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="{row}">
          <el-button
            v-if="row.status === 0"
            size="mini"
            type="primary"
            @click="handleSubmit(row)"
          >
            提交
          </el-button>
          <el-button
            v-if="row.status === 1"
            size="mini"
            type="warning"
            @click="handleCancel(row)"
          >
            取消
          </el-button>
          <el-button
            v-if="row.status === 2"
            size="mini"
            type="success"
            @click="handleArchive(row)"
          >
            归档
          </el-button>
          <el-button
            size="mini"
            type="info"
            @click="handleCirculate(row)"
          >
            传阅
          </el-button>
          <el-dropdown>
            <el-button size="mini">
              更多<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleUpdate(row)">编辑</el-dropdown-item>
              <el-dropdown-item @click.native="handleDelete(row)">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 编辑表单对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="width: 80%; margin: 0 auto;"
      >
        <el-form-item label="文档标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="文档类型" prop="docType">
          <el-select v-model="temp.docType" class="filter-item">
            <el-option
              v-for="item in docTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急程度" prop="urgencyLevel">
          <el-select v-model="temp.urgencyLevel" class="filter-item">
            <el-option
              v-for="item in urgencyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密级" prop="securityLevel">
          <el-select v-model="temp.securityLevel" class="filter-item">
            <el-option
              v-for="item in securityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文档内容" prop="content">
          <el-input
            v-model="temp.content"
            type="textarea"
            :rows="6"
            placeholder="请输入文档内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            :action="uploadUrl"
            :data="{documentId: temp.id}"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :file-list="fileList"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 传阅对话框 -->
    <el-dialog title="文档传阅" :visible.sync="circulateVisible" width="40%">
      <el-form :model="circulateForm" label-width="80px">
        <el-form-item label="传阅对象">
          <el-select
            v-model="circulateForm.userIds"
            multiple
            filterable
            placeholder="请选择传阅对象"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="circulateVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCirculate">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDocument,
  getDocument,
  addDocument,
  updateDocument,
  deleteDocument,
  submitDocument,
  cancelDocument,
  archiveDocument,
  circulateDocument,
  uploadAttachment,
  deleteAttachment
} from '@/api/workflow/document'
import { listUsers } from '@/api/system/user'
import Pagination from '@/components/Pagination'
import DataIO from '@/components/DataIO'

export default {
  name: 'Document',
  components: { Pagination, DataIO },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        keyword: undefined,
        docType: undefined,
        status: undefined
      },
      docTypeOptions: [
        { label: '公文', value: 1 },
        { label: '合同', value: 2 },
        { label: '请示', value: 3 },
        { label: '报告', value: 4 }
      ],
      urgencyOptions: [
        { label: '普通', value: 1 },
        { label: '紧急', value: 2 },
        { label: '特急', value: 3 }
      ],
      securityOptions: [
        { label: '普通', value: 1 },
        { label: '秘密', value: 2 },
        { label: '机密', value: 3 }
      ],
      statusOptions: [
        { label: '草稿', value: 0 },
        { label: '审批中', value: 1 },
        { label: '已完成', value: 2 },
        { label: '已取消', value: 3 },
        { label: '已归档', value: 4 }
      ],
      temp: {
        id: undefined,
        title: '',
        docType: 1,
        urgencyLevel: 1,
        securityLevel: 1,
        content: '',
        status: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑文档',
        create: '新建文档'
      },
      rules: {
        title: [{ required: true, message: '请输入文档标题', trigger: 'blur' }],
        docType: [{ required: true, message: '请选择文档类型', trigger: 'change' }],
        urgencyLevel: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
        securityLevel: [{ required: true, message: '请选择密级', trigger: 'change' }],
        content: [{ required: true, message: '请输入文档内容', trigger: 'blur' }]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/workflow/document/upload',
      fileList: [],
      circulateVisible: false,
      circulateForm: {
        documentId: undefined,
        userIds: []
      },
      userOptions: [],
      // 导出相关配置
      exportColumns: [
        { prop: 'title', label: '文档标题' },
        { prop: 'docType', label: '文档类型' },
        { prop: 'urgencyLevel', label: '紧急程度' },
        { prop: 'securityLevel', label: '密级' },
        { prop: 'status', label: '状态' },
        { prop: 'createUserName', label: '创建人' },
        { prop: 'createTime', label: '创建时间' }
      ],
      pdfOptions: {
        title: '文档记录',
        table: {
          styles: { cellPadding: 2, fontSize: 8 },
          headerStyles: { fillColor: [41, 128, 185], textColor: 255 }
        }
      }
    }
  },
  created() {
    this.getList()
    this.getUserOptions()
  },
  methods: {
    getList() {
      this.listLoading = true
      listDocument(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.temp = {
        id: undefined,
        title: '',
        docType: 1,
        urgencyLevel: 1,
        securityLevel: 1,
        content: '',
        status: 0
      }
      this.fileList = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addDocument(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '创建成功'
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateDocument(tempData).then(() => {
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '更新成功'
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该文档?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDocument(row.id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      })
    },
    handleSubmit(row) {
      this.$confirm('确认提交该文档?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submitDocument(row.id).then(() => {
          this.$message({
            type: 'success',
            message: '提交成功!'
          })
          this.getList()
        })
      })
    },
    handleCancel(row) {
      this.$confirm('确认取消该文档?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelDocument(row.id).then(() => {
          this.$message({
            type: 'success',
            message: '取消成功!'
          })
          this.getList()
        })
      })
    },
    handleArchive(row) {
      this.$confirm('确认归档该文档?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        archiveDocument(row.id).then(() => {
          this.$message({
            type: 'success',
            message: '归档成功!'
          })
          this.getList()
        })
      })
    },
    handleCirculate(row) {
      this.circulateForm.documentId = row.id
      this.circulateForm.userIds = []
      this.circulateVisible = true
    },
    submitCirculate() {
      if (this.circulateForm.userIds.length === 0) {
        this.$message.warning('请选择传阅对象')
        return
      }
      circulateDocument(this.circulateForm.documentId, this.circulateForm.userIds).then(() => {
        this.circulateVisible = false
        this.$message({
          type: 'success',
          message: '传阅成功!'
        })
      })
    },
    handleUploadSuccess(response, file) {
      this.$message.success('上传成功')
      this.getList()
    },
    handleUploadError(err) {
      this.$message.error('上传失败: ' + err.message)
    },
    async getUserOptions() {
      const res = await listUsers()
      this.userOptions = res.data
    },
    getDocTypeName(type) {
      const found = this.docTypeOptions.find(item => item.value === type)
      return found ? found.label : ''
    },
    getUrgencyName(level) {
      const found = this.urgencyOptions.find(item => item.value === level)
      return found ? found.label : ''
    },
    getUrgencyType(level) {
      const map = {
        1: '',
        2: 'warning',
        3: 'danger'
      }
      return map[level]
    },
    getSecurityName(level) {
      const found = this.securityOptions.find(item => item.value === level)
      return found ? found.label : ''
    },
    getSecurityType(level) {
      const map = {
        1: '',
        2: 'warning',
        3: 'danger'
      }
      return map[level]
    },
    getStatusName(status) {
      const found = this.statusOptions.find(item => item.value === status)
      return found ? found.label : ''
    },
    getStatusType(status) {
      const map = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger',
        4: ''
      }
      return map[status]
    },
    handleImport(data) {
      // 处理导入的数据
      console.log('Imported data:', data)
      this.$message.success(`成功导入 ${data.length} 条数据`)
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
}
</style> 